package org.iot.iotserver.netty.command;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import io.netty.channel.ChannelHandlerContext;
import org.iot.iotserver.netty.config.NettyConstant;
import org.iot.iotserver.netty.entity.ADevice;
import org.iot.iotserver.service.IIOTCommonService;

import java.util.Arrays;
import java.util.Map;

/**
 * 处理单片机端数据上报数据
 */
public class DataReportingCommandExecutor implements IYCommandExecutor<String> {

    private static final Log log = LogFactory.get();

    private final IIOTCommonService iotCommonService;

    public DataReportingCommandExecutor(IIOTCommonService iotCommonService) {
        this.iotCommonService = iotCommonService;
    }

    @Override
    public boolean isMatching(String commandMetaData) {
        if(StrUtil.isEmpty(commandMetaData)) {
            return false;
        }
        String[] arr = commandMetaData.split("\\s+");
        if(arr.length < 3 || !"data-reporting".equalsIgnoreCase(arr[0])) {
            return false;
        }
        return true;
    }

    /**
     * 设备端设备数据上送的监控信息保存至缓存
     * @param args 第一个参数代表设备名称, 第二个参数上送设备数据, 格式为: key1=value1;key2=value2
     */
    @Override
    public String execute(ChannelHandlerContext context, String... args) {
        log.info("DataReportingCommandExecutor({})", Arrays.toString(args));

        String deviceName = args[0];
        if(!NettyConstant.LEGAL_DEVICE_NAMES.contains(deviceName)) {
            throw new RuntimeException("非法客户端上送数据");
        }

        ADevice device = NettyConstant.DEVICE_CACHE.get(deviceName);
        device.setStatus(NettyConstant.DeviceStatus.ACTIVE);
        device.setLastAccessTime(System.currentTimeMillis());

        Map<String, String> dataMap = device.getData();
        String attrStrs = args[1];

        for (String attrStr : attrStrs.split("\\s*\\;\\s*")) {
            String[] entryArr = attrStr.split("\\s*\\=\\s*");
            if(dataMap.containsKey(entryArr)) {
                dataMap.replace(entryArr[0], entryArr[1]);
            } else {
                dataMap.put(entryArr[0], entryArr[1]);
            }
        }

        return "OK\r\n";
    }
}
